package cn.schoolwow.quickdao.test.module.business.user.dql.general.testcase;

import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.test.entity.User;
import cn.schoolwow.quickdao.test.module.business.user.dml.user.testcase.AddUserTestCaseFlow;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.alibaba.fastjson.JSONArray;
import org.junit.Assert;

import java.util.Arrays;

public class JSONFieldQueryTestCaseFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        flowContext.executeFlowList(new AddUserTestCaseFlow());

        instanceQuery(flowContext);
        jsonArrayQuery(flowContext);
        jsonConditionQuery(flowContext);
    }

    @Override
    public String name() {
        return "JSON字段类型返回";
    }

    private void instanceQuery(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        User user = dao.query(User.class)
                .addQuery("username", "user0")
                .limit(0,1)
                .execute()
                .getOne();
        Assert.assertTrue(user.getExtraData().containsKey("age"));
        Assert.assertEquals(0, user.getExtraData().getIntValue("age"));
    }

    private void jsonArrayQuery(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        JSONArray array = dao.query(User.class)
                .addQuery("username", "user0")
                .execute()
                .getArray();
        Assert.assertEquals(1, array.size());
    }

    private void jsonConditionQuery(FlowContext flowContext){
        DAO dao = flowContext.checkInstanceData(DAO.class);

        User user = dao.query(User.class)
                .addJSONQuery("extraData", "age", "=","0")
                .addJSONQuery("extraData", "age", "in", Arrays.asList("0","1","2"))
                .execute()
                .getOne();
        Assert.assertTrue(user.getExtraData().containsKey("age"));
        Assert.assertEquals(0, user.getExtraData().getIntValue("age"));
    }

}
